#include "MyGUI.h"
#include "MySQL.h"

GtkWidget *vbox;
GtkWidget *sw;
GtkWidget *window;
GtkWidget *treeview;

void My_GUI::get_iter_last( GtkTreeModel *mdl, GtkTreeIter *itr )
{
  GtkTreeIter i;
  if ( gtk_tree_model_get_iter_first( mdl, &i ) ) {
    while ( gtk_tree_model_iter_next( mdl, &i ) ) {
      *itr = i;
    }
  }
}

void My_GUI::add_item (GtkWidget *button, gpointer data)
{
  GtkTreeIter iter;
  GtkTreeModel *model = items_model;

  gtk_list_store_append (GTK_LIST_STORE (model), &iter);
  for(int i=0;i<=fld_cnt;i++)
  {
	  if (TypeArr[i]==G_TYPE_STRING) gtk_list_store_set (GTK_LIST_STORE (model), &iter, i, "***", -1);
	  else if (TypeArr[i]==G_TYPE_INT) gtk_list_store_set (GTK_LIST_STORE (model), &iter, i, 0, -1);
	  else if (TypeArr[i]==G_TYPE_BOOLEAN) gtk_list_store_set (GTK_LIST_STORE (model), &iter, i, FALSE, -1);
  }
}

void My_GUI::remove_item (GtkWidget *widget, gpointer data)
{
  GtkTreeIter iter;
  GtkTreeView *tree = (GtkTreeView *)treeview;
  GtkTreeModel *model = items_model;
  GtkTreeSelection *selection = gtk_tree_view_get_selection (tree);
  get_iter_last(model, &iter);

  if (gtk_tree_selection_get_selected (selection, NULL, &iter))
    {
      GtkTreePath *path;

      path = gtk_tree_model_get_path (model, &iter);

	  gtk_list_store_remove (GTK_LIST_STORE (model), &iter);

	  gtk_tree_path_free (path);

	  //counter--;
   }
}

gboolean My_GUI::separator_row (GtkTreeModel *model,
               GtkTreeIter  *iter,
               gpointer      data)
{
  GtkTreePath *path;
  gint idx;

  path = gtk_tree_model_get_path (model, iter);
  idx = gtk_tree_path_get_indices (path)[0];

  gtk_tree_path_free (path);

  return idx == 5;
}

void My_GUI::editing_started (GtkCellRenderer *cell,
                 GtkCellEditable *editable,
                 const gchar     *path,
                 gpointer         data)
{
  gtk_combo_box_set_row_separator_func (GTK_COMBO_BOX (editable),
                                        separator_row, NULL, NULL);
}

void My_GUI::cell_edited (GtkCellRendererText *cell,
             const gchar         *path_string,
             const gchar         *new_text,
             gpointer             data)
{
  GtkTreeModel *model = (GtkTreeModel *)data;
  GtkTreePath *path = gtk_tree_path_new_from_string (path_string);
  GtkTreeIter iter;

  gint column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (cell), "column"));

  gtk_tree_model_get_iter (model, &iter, path);

	  if (TypeArr[column]==G_TYPE_STRING)
	  {
	      gchar *old_text;
	      gtk_tree_model_get (model, &iter, column, &old_text, -1);
	      g_free (old_text);
		  gtk_list_store_set (GTK_LIST_STORE (model), &iter, column, g_strdup (new_text), -1);
	  }
	  else if (TypeArr[column]==G_TYPE_INT) gtk_list_store_set (GTK_LIST_STORE (model), &iter, column, atoi (new_text), -1);

  gtk_tree_path_free (path);
}

void My_GUI::fixed_toggled (GtkCellRendererToggle *cell,
               gchar                 *path_str,
               gpointer               data)
{
  GtkTreeModel *model = (GtkTreeModel *)data;
  GtkTreeIter  iter;
  GtkTreePath *path = gtk_tree_path_new_from_string (path_str);
  gboolean fixed;
  gint column = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (cell), "column"));;

  /* get toggled iter */
  gtk_tree_model_get_iter (model, &iter, path);
  gtk_tree_model_get (model, &iter, column, &fixed, -1);

  /* do something with the value */
  fixed ^= 1;

  /* set new value */
  gtk_list_store_set (GTK_LIST_STORE (model), &iter, column, fixed, -1);

  /* clean up */
  gtk_tree_path_free (path);
}

void My_GUI::add_columns (GtkTreeView  *treeview,
             GtkTreeModel *items_model,
             GtkTreeModel *products_model)
{
  GtkCellRenderer *renderer;
  GtkTreeViewColumn *column;

  for(int i=0;i<=fld_cnt;i++)
  {
	  if (TypeArr[i]==G_TYPE_STRING)
	  {
		  renderer = gtk_cell_renderer_combo_new ();

		  g_object_set (renderer,
		                "model", products_model,
		                "text-column", COLUMN_PRODUCT_TEXT,
		                "has-entry", TRUE,
		                "editable", TRUE,
		                NULL);
		  g_signal_connect (renderer, "edited",
		                    G_CALLBACK (cell_edited), items_model);
		  g_signal_connect (renderer, "editing-started",
		                    G_CALLBACK (editing_started), NULL);
		  g_object_set_data (G_OBJECT (renderer), "column", GINT_TO_POINTER (i));
		  column = gtk_tree_view_column_new_with_attributes (fld_arr[i].c_str(),
		                                                     renderer,
		                                                     "text",
		                                                     i,
		                                                     NULL);
		  gtk_tree_view_column_set_sort_column_id (column, i);
		  gtk_tree_view_append_column (treeview, column);
	  }
	  else if (TypeArr[i]==G_TYPE_INT)
	  {
		  renderer = gtk_cell_renderer_text_new ();
		  g_object_set (renderer, "editable", TRUE, NULL);
		  g_signal_connect (renderer, "edited",
							G_CALLBACK (cell_edited), items_model);
		  g_object_set_data (G_OBJECT (renderer), "column", GINT_TO_POINTER (i));
		  column = gtk_tree_view_column_new_with_attributes (fld_arr[i].c_str(),
															 renderer,
															 "text",
															 i,
															 NULL);
		  gtk_tree_view_column_set_sort_column_id (column, i);
		  gtk_tree_view_append_column (treeview, column);
	  }
	  else if (TypeArr[i]==G_TYPE_BOOLEAN)
	  {
		  renderer = gtk_cell_renderer_toggle_new ();
		  g_signal_connect (renderer, "toggled",
							G_CALLBACK (fixed_toggled), items_model);
		  g_object_set_data (G_OBJECT (renderer), "column", GINT_TO_POINTER (i));
		  column = gtk_tree_view_column_new_with_attributes (fld_arr[i].c_str(),
															 renderer,
															 "active", i,
															 NULL);

		  /* set this column to a fixed sizing (of 50 pixels) */
		  gtk_tree_view_column_set_sizing (GTK_TREE_VIEW_COLUMN (column),
										   GTK_TREE_VIEW_COLUMN_FIXED);
		  gtk_tree_view_column_set_fixed_width (GTK_TREE_VIEW_COLUMN (column), 50);
		  gtk_tree_view_append_column (treeview, column);
	  }
  }
}

void My_GUI::add_treeview()
{
	if(GTK_IS_WIDGET (treeview)) gtk_container_remove (GTK_CONTAINER (sw), treeview);
	/* create models */
    items_model = My_SQL::create_items_model ();
    products_model = My_SQL::create_products_model ();

    /* create tree view */
    treeview = gtk_tree_view_new_with_model (items_model);
    gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeview), TRUE);
    gtk_tree_selection_set_mode (gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)),
                                 GTK_SELECTION_SINGLE);

    add_columns (GTK_TREE_VIEW (treeview), items_model, products_model);

    fld_cnt=0;

    g_object_unref (products_model);
    g_object_unref (items_model);

    gtk_container_add (GTK_CONTAINER (sw), treeview);

    gtk_widget_show_all (window);
}

void My_GUI::interactive_dialog_clicked (GtkButton *button,
			    gpointer   user_data)
{
  GtkWidget *dialog;
  GtkWidget *hbox;
  GtkWidget *stock;
  GtkWidget *table;
  GtkWidget *local_entry1;
  GtkWidget *local_entry2;
  GtkWidget *label;
  gint response;

  dialog = gtk_dialog_new_with_buttons( "Data source",
                                                GTK_WINDOW( window ),
                                                GTK_DIALOG_MODAL,
                                                GTK_STOCK_YES, 1,
                                                GTK_STOCK_NO,  2,
                                                NULL );

  hbox = gtk_hbox_new (FALSE, 8);
  gtk_container_set_border_width (GTK_CONTAINER (hbox), 8);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox, FALSE, FALSE, 0);

  stock = gtk_image_new_from_stock (GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
  gtk_box_pack_start (GTK_BOX (hbox), stock, FALSE, FALSE, 0);

  table = gtk_table_new (2, 2, FALSE);
  gtk_table_set_row_spacings (GTK_TABLE (table), 4);
  gtk_table_set_col_spacings (GTK_TABLE (table), 4);
  gtk_box_pack_start (GTK_BOX (hbox), table, TRUE, TRUE, 0);
  label = gtk_label_new_with_mnemonic ("_SQL 1");
  gtk_table_attach_defaults (GTK_TABLE (table),
			     label,
			     0, 1, 0, 1);
  local_entry1 = gtk_entry_new ();
  gtk_entry_set_text (GTK_ENTRY (local_entry1), gtk_entry_get_text (GTK_ENTRY (entry1)));
  gtk_table_attach_defaults (GTK_TABLE (table), local_entry1, 1, 2, 0, 1);
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), local_entry1);

  label = gtk_label_new_with_mnemonic ("S_QL 2");
  gtk_table_attach_defaults (GTK_TABLE (table),
			     label,
			     0, 1, 1, 2);

  local_entry2 = gtk_entry_new ();
  gtk_entry_set_text (GTK_ENTRY (local_entry2), gtk_entry_get_text (GTK_ENTRY (entry2)));
  gtk_table_attach_defaults (GTK_TABLE (table), local_entry2, 1, 2, 1, 2);
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), local_entry2);

  gtk_widget_show_all (hbox);
  response = gtk_dialog_run (GTK_DIALOG (dialog));

  if (response == 1)
    {
      gtk_entry_set_text (GTK_ENTRY (entry1), gtk_entry_get_text (GTK_ENTRY (local_entry1)));
      gtk_entry_set_text (GTK_ENTRY (entry2), gtk_entry_get_text (GTK_ENTRY (local_entry2)));
      add_treeview();
    }

  gtk_widget_destroy (dialog);
}

void My_GUI::activate_action (GtkAction *action)
{
  g_message ("Action \"%s\" activated", gtk_action_get_name (action));
  gtk_widget_destroy (window);
}

void My_GUI::activate_radio_action (GtkAction *action, GtkRadioAction *current)
{
  g_message ("Radio action \"%s\" selected",
	     gtk_action_get_name (GTK_ACTION (current)));
}

gchar * My_GUI::demo_find_file (const char *base, GError    **err)
{
g_return_val_if_fail (err == NULL || *err == NULL, NULL);

if (g_file_test ("gtk-logo-rgb.gif", G_FILE_TEST_EXISTS) &&
g_file_test (base, G_FILE_TEST_EXISTS))
return g_strdup (base);
else
{
char *filename = g_build_filename ("C:/MinGW/gtk+/share/gtk-2.0/demo", base, NULL);
if (!g_file_test (filename, G_FILE_TEST_EXISTS))
{
g_set_error (err, G_FILE_ERROR, G_FILE_ERROR_NOENT,
 "Cannot find demo data file \"%s\"", base);
g_free (filename);
return NULL;
}
return filename;
}
}

void My_GUI::about_cb (GtkAction *action,
	  GtkWidget *window)
{
  GdkPixbuf *pixbuf, *transparent;
  gchar *filename;

  const gchar *authors[] = {
    "Radu Manea who tries",
    "desperately to show that",
    "impossible is nothing and",
    "above misconceptions and",
    "ignorance there's tones of",
    "hypocrisy...",
    NULL
  };

  const gchar *documentors[] = {
    "Radu Manea who tries",
    "desperately to show that",
    "impossible is nothing and",
    "above misconceptions and",
    "ignorance there's tones of",
    "hypocrisy...",
    NULL
  };

  const gchar *license =
    "This is free software; you can redistribute it and/or\n"
    "modify it under the terms of the GNU Library General Public License as\n"
    "published by the Free Software Foundation; either version 2 of the\n"
    "License, or (at your option) any later version.\n"
    "\n"
    "This library is distributed in the hope that it will be useful,\n"
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
    "Library General Public License for more details.\n"
    "\n"
    "You should have received a copy of the GNU Library General Public\n"
    "License along with the Gnome Library; see the file COPYING.LIB.  If not,\n"
    "write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n"
    "Boston, MA 02111-1307, USA.\n";

  pixbuf = NULL;
  transparent = NULL;
  filename = demo_find_file ("gtk-logo-rgb.gif", NULL);
  if (filename)
    {
      pixbuf = gdk_pixbuf_new_from_file (filename, NULL);
      g_free (filename);
      transparent = gdk_pixbuf_add_alpha (pixbuf, TRUE, 0xff, 0xff, 0xff);
      g_object_unref (pixbuf);
    }

  gtk_show_about_dialog (GTK_WINDOW (window),
			 "program-name", "MySQLBrowser",
			 "version", "3.2",
			 "copyright", "(C) 2013 Author",
			 "license", license,
			 "website", "http://mysqlbrowser.codeplex.com/",
			 "comments", "Program to demonstrate GTK+ integration with MySQL CPP connector",
			 "authors", authors,
			 "documenters", documentors,
			 "logo", transparent,
                         "title", "About MySQLBrowser",
			 NULL);

  g_object_unref (transparent);
}

void My_GUI::add_menu()
{
    GtkActionGroup *actions;
    GtkUIManager *ui;
    GError *error = NULL;

    actions = gtk_action_group_new ("Actions");
    gtk_action_group_add_actions (actions, entries, n_entries, NULL);
    gtk_action_group_add_toggle_actions (actions,
         					   toggle_entries, n_toggle_entries,
         					   NULL);
    gtk_action_group_add_radio_actions (actions,
         					  color_entries, n_color_entries,
         					  COLOR_RED,
         					  G_CALLBACK (activate_radio_action),
         					  NULL);
    gtk_action_group_add_radio_actions (actions,
         					  shape_entries, n_shape_entries,
         					  SHAPE_OVAL,
         					  G_CALLBACK (activate_radio_action),
         					  NULL);

    ui = gtk_ui_manager_new ();
    gtk_ui_manager_insert_action_group (ui, actions, 0);
    g_object_unref (actions);
    gtk_window_add_accel_group (GTK_WINDOW (window),
    gtk_ui_manager_get_accel_group (ui));

    if (!gtk_ui_manager_add_ui_from_string (ui, ui_info, -1, &error))
         	{
         	  g_message ("building menus failed: %s", error->message);
         	  g_error_free (error);
         	}

    gtk_box_pack_start (GTK_BOX (vbox),
         			  gtk_ui_manager_get_widget (ui, "/MenuBar"),
         			  FALSE, FALSE, 0);
}
